<?php

/**
 * 日志记录类
 */
class Logger {
    const DEBUG = 0;
    const INFO = 1;
    const WARNING = 2;
    const ERROR = 3;

    private static $logLevel = self::INFO;
    private static $logFile = null;

    /**
     * 设置日志级别
     */
    public static function setLevel($level) {
        self::$logLevel = $level;
    }

    /**
     * 设置日志文件
     */
    public static function setLogFile($file) {
        self::$logFile = $file;

        // 确保日志目录存在
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }

    /**
     * 记录调试信息
     */
    public static function debug($message, $context = []) {
        self::log(self::DEBUG, 'DEBUG', $message, $context);
    }

    /**
     * 记录一般信息
     */
    public static function info($message, $context = []) {
        self::log(self::INFO, 'INFO', $message, $context);
    }

    /**
     * 记录警告信息
     */
    public static function warning($message, $context = []) {
        self::log(self::WARNING, 'WARNING', $message, $context);
    }

    /**
     * 记录错误信息
     */
    public static function error($message, $context = []) {
        self::log(self::ERROR, 'ERROR', $message, $context);
    }

    /**
     * 记录日志
     */
    private static function log($level, $levelName, $message, $context = []) {
        if ($level < self::$logLevel) {
            return;
        }

        $timestamp = date('Y-m-d H:i:s');
        $contextStr = empty($context) ? '' : ' ' . json_encode($context, JSON_UNESCAPED_UNICODE);
        $logMessage = "[{$timestamp}] [{$levelName}] {$message}{$contextStr}" . PHP_EOL;

        // 输出到控制台
        echo $logMessage;

        // 写入日志文件
        if (self::$logFile) {
            file_put_contents(self::$logFile, $logMessage, FILE_APPEND | LOCK_EX);
        }
    }

    /**
     * 格式化异常信息
     */
    public static function formatException(Exception $e) {
        return sprintf(
            "Exception: %s in %s:%d\nStack trace:\n%s",
            $e->getMessage(),
            $e->getFile(),
            $e->getLine(),
            $e->getTraceAsString()
        );
    }

    public static function setUserLoginFile($phone) {
        $file = __DIR__ . '/logs/auto_video_' . $phone . '_' . date('Y-m-d') . '.log';
        self::$logFile = $file;

        // 确保日志目录存在
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

    }
}

// 设置默认日志文件
Logger::setLogFile(__DIR__ . '/logs/auto_video_' . date('Y-m-d') . '.log');
